<template>
	<div class="div1">
		<el-backtop target=".div1"></el-backtop>
		<!-- 头部 -->

		<Head :data="searchList" style="background: #fff;"></Head>
		<!-- 中部内容 -->
		<div style="background: #F6F5F7;">
			<div class="tong">
				<div class="content-top">
					<div class="save-address">{{$t('placeOrder.Consignee')}} <span class="xintian" @click="tianjia()">{{$t('placeOrder.NewlyFilledDeliveryAddress')}}</span></div>
					<div v-if="checkAddress == true">
						<div class="user-msg" style="display: flex" v-for="(item, index) in editAddress" :key="index"
							@click="selectAddress(item)">
							<div class="name">
								<img v-if="item.select" src="../../../static/images/order/23.png" alt="">
								<div class="user-name">{{ item.provinces }} ({{ item.consignee }}{{$t('shopCartOrder.receive')}})</div>
							</div>
							<div class="address">{{ item.detail }} （ {{ $t('login.MobilePhoneNumber') }}{{ item.mobile }} ）</div>
						</div>
					</div>
					<div v-if="checkAddress == false">
						{{ $t('placeOrder.ThereIsNoAddress') }}
					</div>
					<img src="../../assets/index/caitiao.png" class="caitiao" />
				</div>
			</div>

			<div class="tong three">
				<div class="content-top1">
					<div class="save-address">{{ $t('placeOrder.commodity') }}</div>
					<div>
						<el-table :data="tableData" style="width: 100%">
							<el-table-column prop="date" :label="$t('placeOrder.GoodsInformation')" width="350">
								<template slot-scope="scope">
									<div>
										<img :src="scope.row.goods.coverImg" class="imgs" />
										<div class="rights">
											<div class="title">{{ scope.row.goods.title }}</div>
											<div class="guige">{{ $t('placeOrder.specifications') }}:{{ scope.row.sku ?
												scope.row.sku.detailJson : '' }}</div>
										</div>
									</div>
								</template>
							</el-table-column>
							<el-table-column v-if="relationId != 'null'" prop="goods.memberPrice"
								:label="$t('placeOrder.unitPrice') + '(' + $t('placeOrder.yuan') + ')'">
								<template slot-scope="scope">
									<div>{{ getProportion(scope.row.goods.memberPrice) }}</div>
								</template>
							</el-table-column>
							<el-table-column v-else prop="goods.price"
								:label="$t('placeOrder.unitPrice') + '(' + $t('placeOrder.yuan') + ')'">
								<template slot-scope="scope">
									<div>{{ getProportion(scope.row.goods.price) }}</div>
								</template>
							</el-table-column>
							<el-table-column prop="number" :label="$t('goodsDet.quantity')">
								<template slot-scope="scope">
									<div>
										<el-input-number size="mini" v-model="scope.row.number"
											@change="handleChange(scope.row, scope.$index)" :min="1" step-strictly>
										</el-input-number>
									</div>
								</template>
							</el-table-column>
							<el-table-column prop="zsp"
								:label="$t('placeOrder.money') + '(' + $t('placeOrder.yuan') + ')'">
								<template slot-scope="scope">
									<div v-if="relationId != 'null'">{{ getProportion(scope.row.number *
										scope.row.goods.memberPrice) }}</div>
									<div v-if="relationId == 'null'">{{ getProportion(scope.row.number *
										scope.row.goods.price)
										}}</div>
								</template>
							</el-table-column>
							<el-table-column prop="goods.postagePrice"
								:label="$t('placeOrder.transportation') + '(' + $t('placeOrder.yuan') + ')'">
								<template slot-scope="scope">
									<div>{{ getProportion(scope.row.goods.postagePrice) }}</div>
								</template>
							</el-table-column>
						</el-table>
						<div class="liuyan">{{ $t('placeOrder.toTheSeller') }}：
							<!--							<textarea :value = "liuyan" name = "" id = "" cols = "50" rows = "10"-->
							<!--									  placeholder = "可以告诉卖家您的特殊需求，需要和卖家协商一致"></textarea>-->
							<input type="text" class="ly" v-model="liuyan" :placeholder="$t('placeOrder.YouCan')">
						</div>
						<div class="zje">{{ $t('placeOrder.amountOfGoods') }}：<span class="zjeS">{{
							getProportion(zongjineSp) }}{{ DollarSignValue
								}}</span></div>
						<div class="zje">{{ $t('placeOrder.freight') }}：<span class="zjeS">{{ getProportion(zongjineYf)
								}}{{ DollarSignValue
								}}</span></div>
						<div class="right">
							<div class="rightT">
								<div class="zje">{{ $t('placeOrder.Actualpayment') }}：<span class="zjeS">{{
									getProportion(zongjine) }}{{
											DollarSignValue }}</span></div>
								<div class="psdz">{{ $t('placeOrder.SendTo') }}：<span class="dz">{{ provinces }}
										{{ detail }}</span></div>
								<div class="shr">{{ $t('placeOrder.consignee') }}：{{ consignee }} {{ mobile }}</div>
							</div>
							<button class="tijiao" @click="goPay()">{{ $t('placeOrder.SubmitOrder') }}</button>
						</div>
					</div>
				</div>
			</div>
		</div>
		<!-- 底部 -->
		<Foots></Foots>
	</div>
</template>

<script>
import Head from '@/components/head.vue'
import Foots from '@/components/foots.vue'
import goodsItem from "../../components/goods-item";
import { currency } from '../js/currency'
import {
	Loading
} from 'element-ui';
export default {
	components: {
		Head,
		Foots,
		goodsItem
	},
	data() {
		return {
			page: 1,
			searchList: ['粽子', '防晒霜', '洗衣液', '蚊香液', '抽纸', '零食'],
			tableData: [],
			liuyan: '',
			zongjine: 0,
			zongjineSp: 0,
			zongjineYf: 0,
			checkString: '', //规格
			numberMoney: '', //单价
			number: 1, //购买数量
			editAddress: {},
			checkAddress: false,
			detail: '',
			consignee: '',
			mobile: '',
			provinces: '',
			isExpress: 1,
			addressId: '',
			list: {},
			skuId: 0,
			commissionPrice: 0,
			orderId: 0,//订单id
			ids: [],
			numceshinum: 0,
			priceFeiList: [],//正确的运费列表
			relationId: window.localStorage.getItem('relationId'),	//邀请码
		}
	},
	created() {
		this.tableData = JSON.parse(window.localStorage.getItem('shopCartOrderList'))
		this.ids = this.$route.query.ids

	},
	mounted() {
		setTimeout(()=>{
			this.getAddressList();
		},500)
	},
	computed: {
		DollarSignValue() {
			// let dollar=this.$store.state.currencyInfo.figure
			let dollar = this.getDollarSign()
			return dollar
		}
	},
	methods: {
		// 获取货币符号
		getDollarSign() {
			let dollar = this.$store.state.currencyInfo.figure
			return dollar
		},
		// 金额计算比例
		getProportion(money) {
			let proportion = this.$store.state.currencyInfo.scale
			let price = currency(proportion, money)
			return price
			// return money
		},
		// 添加地址
		tianjia() {
			this.$router.push({
				path: '/order?select=address'
			})
		},
		// 修改地址
		xiugai(dzId) {
			this.$router.push({
				path: '/order?select=address'
			})
		},
		handleChange(row, index) {
			this.tableData[index].zsp = Number(row.numberMoney) * row.number
			this.list.zsp = Number(row.numberMoney) * row.number
			this.tableData[index].number = row.number
			// this.jisuan()
			this.getMeteringAll()
		},
		jisuan() {
			var zyf = 0
			var zsp = 0

			var tableData = this.tableData
			for (var i in tableData) {
				if (tableData[i].goods.postagePrice) {
					zyf = zyf + Number(tableData[i].goods.postagePrice)
				}
				if (this.relationId != 'null') {
					this.tableData[i].zsp = (Number(tableData[i].goods.memberPrice) * Number(tableData[i].number)).toFixed(2)
					zsp = zsp + (Number(tableData[i].goods.memberPrice) * Number(tableData[i].number)).toFixed(2) * 1
				} else {
					this.tableData[i].zsp = (Number(tableData[i].goods.price) * Number(tableData[i].number)).toFixed(2)
					zsp = zsp + (Number(tableData[i].goods.price) * Number(tableData[i].number)).toFixed(2) * 1
				}
			}
			this.list = this.tableData[0]
			this.zongjineSp = zsp.toFixed(2)
			this.zongjineYf = zyf.toFixed(2)
			this.zongjine = (this.zongjineYf * 1 + this.zongjineSp * 1).toFixed(2)
		},
		//获取地址列表
		getAddressList() {
			let userId = this.$cookie.get('userId');
			this.$http({
				url: this.$http.adornUrl('/address/findByUserId'),
				method: 'get',
				params: this.$http.adornParams({
					'userId': userId
				})
			}).then(({ data }) => {
				if (data.status == 0) {
					if (data.data) {
						data.data.forEach(res => {
							// this.provinces = res.provinces;
							// this.detail = res.detail;
							// this.consignee = res.consignee;
							// this.mobile = res.mobile;

							if (res.isDefault) {
								console.log('aadizhiaa', res)
								res.select = 1
								this.provinces = res.provinces;
								this.detail = res.detail;
								this.consignee = res.consignee;
								this.mobile = res.mobile;
								this.addressId = res.id;
							} else {
								res.select = 0
								this.provinces = data.data[0].provinces
								this.detail = data.data[0].detail
								this.consignee = data.data[0].consignee
								this.mobile = data.data[0].mobile
								this.addressId = data.data[0].id
							}
						})

						this.editAddress = data.data
						this.checkAddress = true;
					} else {
						this.checkAddress = false;
					}
					this.getMeteringAll()
				} else {
					this.checkAddress = false;
				}
			})
		},
		//选择地址
		selectAddress(e) {
			this.editAddress.forEach(res => {
				if (res.id == e.id) {
					res.select = 1
					this.provinces = res.provinces;
					this.detail = res.detail;
					this.consignee = res.consignee;
					this.mobile = res.mobile;
					this.addressId = res.id
					this.getMeteringAll()
				} else {
					res.select = 0
				}
			})
		},
		orderDel() {
			this.$http({
				url: this.$http.adornUrl('/selfCart/deleteAll?ids=' + this.ids),
				method: 'get',
				params: this.$http.adornParams({})
			}).then(({ data }) => {
				console.log('删除商品')
			})
		},
		// 支付订单
		goPay() {
			if (this.editAddress.length == 0) {
				this.$notify({
					title: '提示',
					message: '请设置收货地址信息',
					type: 'warning'
				});
				return;
			}
			const loading = this.$loading({
				lock: true,
				text: '订单生成中···',
				spinner: 'el-icon-loading',
				background: 'rgba(0, 0, 0, 0.7)'
			});
			this.orderDel()
			let userId = this.$cookie.get('userId');
			let datas = [];
			console.log(this.tableData, '******')
			for (var i = 0; i < this.tableData.length; i++) {
				let data = {
					userId: userId,
					status: '1',
					orderType: '1',
					consignee: this.consignee,
					mobile: this.mobile,
					provinces: this.provinces,
					detail: this.detail,
					//上面的都是地址信息
					storeId: this.tableData[i].storeId,
					storeName: this.tableData[i].storeName,
					merchantId: this.tableData[i].merchantId,

					couponMoney: '', //这个是优惠券金额，替换了descrition的值描述
					userCouponsId: this.tableData[i].goods.brandId, //这个是优惠券id，替换了brandID的值（品牌ID）
					type: this.tableData[i].goods.typeId,
					title: this.tableData[i].goods.title,
					goodsId: this.tableData[i].goodsId,
					img: this.tableData[i].goods.coverImg,
					isExpress: '1',
					descrition: this.liuyan, //备注信息，稍后需要另改
					skuId: this.tableData[i].skuId,
					price: this.relationId != 'null' ? this.tableData[i].goods.memberPrice : this.tableData[i].goods.price,
					number: this.tableData[i].number,
					postagePrice: this.tableData[i].goods.postagePrice,
					payMoney: this.tableData[i].zsp * 1 + this.tableData[i].goods.postagePrice * 1,
					relationId: this.relationId,
					detailJson: this.tableData[i].sku ? this.tableData[i].sku.detailJson : '',
					commissionPrice: this.tableData[i].goods.memberPrice * this.tableData[i].goods.commissionPrice
				}
				datas.push(data);
			}
			this.$http({
				url: this.$http.adornUrl('/orders/saveAll'),
				method: 'post',
				data: this.$http.adornData(datas)
			}).then(res => {
				loading.close();
				if (res.status == 200) {
					let id = []
					let goodsId = []
					res.data.data.forEach(ret => {
						id.push(ret.id)
						goodsId.push(ret.goodsId)
					})

					this.$router.push({
						path: '/payment?payNum=' + res.data.data[0].payNum + '&money=' + this.zongjine + '&id=' + id.toString()
							+ '&goodsId=' + this.ids
					})
				}
			});
		},

		// 关闭弹框
		handleClose(done) {
			this.dialogVisible = false
		},
		// 获取运费
		getMeteringAll() {
			let loadingInstance = Loading.service({
				lock: true,
				text: '加载中……',
				background: 'rgba(0, 0, 0, 0.7)'
			});
			let data = []
			let _that = this
			
			this.tableData.forEach((item) => {
				data.push({
					addressId: _that.addressId,
					goodId: item.goodsId,
					sum: item.number
				})
			})
			this.$http({
				url: this.$http.adornUrl('/selfMetering/meteringAll'),
				method: 'post',
				data: this.$http.adornData(data),
			}).then(res => {
				this.$nextTick(() => {
					loadingInstance.close();
				})
				if (res.data.status == 0) {
					let priceFei = res.data.data.data
					this.priceFeiList = priceFei
					let dataObjList = []
					if (this.tableData.length > 0) {
						dataObjList = this.tableData
					} else {
						dataObjList = JSON.parse(window.localStorage.getItem('shopCartOrderList'))
					}
					for (let i = 0; i < this.priceFeiList.length; i++) {
						let itemObj = this.priceFeiList[i]
						for (let g = 0; g < dataObjList.length; g++) {
							let itemObjY = dataObjList[g]
							if (itemObj.id == itemObjY.goodsId) {
								itemObjY.goods.postagePrice = itemObj.postagePrice
							}
						}
					}
					this.tableData = dataObjList
					this.jisuan()
				}
			})
		},
	}
}
</script>

<style scoped>
.div1 {
	height: 100vh;
	overflow-x: hidden;
}


/* 第一部分 */
.tong {
	width: 1200px;
	margin: 0 auto;
	margin-top: 15px;
}

.three {
	margin-bottom: 80px;
}

.content-top {
	/* width: 880px; */
	padding: 20px 20px 0 20px;
	border-radius: 6px;
	background: #fff !important;
}

.content-top1 {
	/* width: 880px; */
	padding: 20px;
	border-radius: 6px;
	background: #fff !important;
}

.save-address {
	color: #333333;
	font-weight: 700;
	font-size: 18px;
	position: relative;
}

.xintian {
	position: absolute;
	right: 0;
	display: inline-block;
	font-size: 12px;
	color: #5293FF;
	font-weight: 500;
}

.user-msg {
	margin: 20px 0;
}

.name {
	position: relative;
	text-align: center;
	line-height: 34px;
}

.name>img {
	position: absolute;
	top: 0;
	left: 0;
	width: 100%;
	height: 34px;
}

.user-name {
	margin: 0 8px;
	font-width: 700;
	font-size: 16px;
}

.address {
	line-height: 34px;
	margin-left: 20px;
	color: #999999;
	font-size: 16px;
}

.updata-address {
	font-size: 14px;
	color: #d0a182;
	/*margin-top: 20px;*/
}

.caitiao {
	width: 100%;
}

.imgs {
	width: 80px;
	height: 80px;
	float: left;
}

.rights {
	margin-left: 90px;
}

.title {
	word-break: break-all;
	text-overflow: ellipsis;
	overflow: hidden;
	display: -webkit-box;
	-webkit-line-clamp: 2;
	-webkit-box-orient: vertical;
}

.guige {
	margin-top: 6px;
	color: #999;
	font-size: 14px;
}

.liuyan {
	font-size: 13px;
	color: #333;
	margin: 30px 0;
}

.ly {
	margin-left: 10px;
	line-height: 25px;
	height: 25px;
	border: 1px solid #DDDDDD;
	width: 300px;
	padding: 0 15px;
	font-size: 12px;
}

.zje {
	font-size: 14px;
	line-height: 24px;
}

.zjeS {
	color: #EA7408;
	font-weight: 600;
	display: inline-block;
	font-size: 18px;
}

.right {
	text-align: right;
	margin-top: 10px;
}

.rightT {
	width: 40%;
	border: 1px solid #EA7408;
	padding: 20px;
	margin-left: 60%;
	box-sizing: border-box;
}

.psdz {
	margin-top: 20px;
	color: #333;
	font-size: 14px;

}

.dz {
	color: #999999;
}

.shr {
	margin-top: 10px;
	color: #333;
	font-size: 14px;
}

.tijiao {
	margin-top: 20px;
	width: 180px;
	height: 50px;
	line-height: 50px;
	color: #fff;
	background: #EA7408;
	border: 1px solid #EA7408;
	font-size: 15px;

}
</style>
